package com.novel.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.novel.bean.CrawlerBean;
import com.novel.bean.ResultDomain;
import com.novel.bean.SectionBean;
import com.novel.service.CrawlerService;
import com.novel.task.CrawlerSectionTask;
import com.novel.utils.CacheUtil;
import com.novel.utils.JsonUtil;

@WebServlet("/crawler")
public class CrawlerAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public CrawlerAction() {
        super();
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Access-Control-Allow-Origin", "*");  
		response.setHeader("Access-Control-Allow-Methods", "*");  
		response.setHeader("Access-Control-Allow-Headers", "*");
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("image/gif; charset=utf-8");
		
		String method=request.getParameter("method");//得到传入的值下面根据传入的值执行不同的方法！！
        if(method.equals("single")){
        	singleBook(request, response);
        }
        if(method.equals("allsite")) {
        }
        if(method.equals("singletest")) {
        	singleTest(request, response);
        }
        if(method.equals("stopbook")) {
        	stopBook(request, response);
        }
        if(method.equals("continue")) {
        	continueBook(request, response);
        }
        if(method.equals("queryproc")) {
        	queryproc(request, response);
        }
	}

	private void queryproc(HttpServletRequest request, HttpServletResponse response) {
		ResultDomain ret = new ResultDomain();
		Map<Long, CrawlerSectionTask> secTask = CacheUtil.getInstance().getCrawlerSectionTask();
		if(secTask == null || secTask.size() == 0){
			secTask  = new HashMap<>();
			ret.setFail("当前没有正在爬取的书籍");
			out(response,ret);
			return;
		}
		List<Map<String,String>> retList = new ArrayList<>();
		Map<String,String> map = null;
		for (Map.Entry<Long, CrawlerSectionTask> entry : secTask.entrySet()) { 
			map = new HashMap<>();
			map.put("bookid", entry.getKey()+"");
			map.put("bookname", entry.getValue().getBookName());
			map.put("remainSize", entry.getValue().remainNum()+"");
			map.put("delay", entry.getValue().getDelay()+"");
			int delay = (entry.getValue().getDelay()-1000)/300;
			int sleep = delay * 10 + 30;
			map.put("sleep", sleep+"");
			retList.add(map);
		}
		ret.setSuccess("查询成功", retList);
		out(response,ret);
	}

	private void continueBook(HttpServletRequest request, HttpServletResponse response) {
		ResultDomain ret = new ResultDomain();
		String bookid = request.getParameter("bookid");
		if(bookid == null || "".equals(bookid)){
			ret.setFail("bookid不能为空");
			out(response,ret);
			return;
		}
		long id = Long.parseLong(bookid);
		boolean b = CrawlerService.crawlerService.continueBook(id);
		Map<String, Object> map = new HashMap<>();
		if(b){
			map.put("desc", "恢复爬取成功");
		}else{
			map.put("desc", "恢复爬取出错");
		}
		out(response,map);
	}

	private void stopBook(HttpServletRequest request, HttpServletResponse response) {
		ResultDomain ret = new ResultDomain();
		String bookid = request.getParameter("bookid");
		if(bookid == null || "".equals(bookid)){
			ret.setFail("bookid不能为空");
			out(response,ret);
			return;
		}
		long id = Long.parseLong(bookid);
		CrawlerSectionTask task = (CrawlerSectionTask)CacheUtil.getInstance().getCrawlerSectionTask().remove(id);
		CrawlerBean bean = (CrawlerBean)CacheUtil.getInstance().delete(id+"crawler");
		task.stop();
		try {
			Thread.sleep(50);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		List<SectionBean> list = task.getSectionList();
		boolean b = CrawlerService.crawlerService.saveContinue(id,list,bean);
		Map<String, Object> map = new HashMap<>();
		if(b){
			map.put("desc", "持久化书籍未完成章节成功");
		}else{
			map.put("desc", "持久化书籍未完成章节出错");
		}
		out(response,map);
	}

	private void singleTest(HttpServletRequest request, HttpServletResponse response) {
		ResultDomain result = null;
		CrawlerBean bean = null;
		try {
			bean = (CrawlerBean) JsonUtil.request2Domain(request, CrawlerBean.class);
			result = CrawlerService.crawlerService.singleTest(bean);
		} catch (Exception e) {
			result = new ResultDomain();
			result.setFail("参数解析错误",e);
		}
		out(response,result);
	}

	private void singleBook(HttpServletRequest request, HttpServletResponse response) {
		ResultDomain result = null;
		CrawlerBean bean = null;
		try {
			bean = (CrawlerBean) JsonUtil.request2Domain(request, CrawlerBean.class);
			result = CrawlerService.crawlerService.singleBook(bean);
		} catch (Exception e) {
			result = new ResultDomain();
			result.setFail("参数解析错误",e);
		}
		out(response,result);
	}

	private void  out(HttpServletResponse response, Object result) {
		//指定返回的格式为JSON格式
		response.setContentType("text/plain;charset=utf-8");
		
		//setContentType与setCharacterEncoding的顺序不能调换，否则还是无法解决中文乱码的问题
		response.setCharacterEncoding("UTF-8");
		
		String resultStr = JSONObject.toJSONString(result);
		PrintWriter out =null ;
		try {
			out =response.getWriter() ;
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
		out.write(resultStr);
		out.close();
	}
}
